<?php

Yii::import('application.extensions.Util.*');
Yii::import('application.models.UploadImage');

class ProductController extends ControllerBase {

    public function init() {
        parent::init();
        $this->registerFancybox();
    }

    public function registerFancybox() {
        // Add jQuery library
        // ShortUtil::clientScript()->registerCoreScript('jquery');
        // Add mousewheel plugin (this is optional)
        ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

        // Add fancyBox main JS and CSS files
        ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
        ShortUtil::registerCssFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.css?v=2.0.6', 'screen');

        // Add Button helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-buttons.css?v=1.0.2');
        // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-buttons.js?v=1.0.2','screen');
        // Add Thumbnail helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-thumbs.css?v=1.0.2');
        // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-thumbs.js?v=1.0.2','screen');
        // Add Media helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-media.js?v=1.0.0');
        if (isset($_GET['ajax']))
            $this->layout = '//layouts/none';
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $relativeProduct = UploadImage::model()->findAll(array(
            'condition' => 'image_model = "Product" AND image_relative = :proID',
            'params' => array(
                ':proID' => $id
            )
        ));        
        
        $this->render('detail', array(
            'model' => $this->loadModel($id),
            'moreViews' => $relativeProduct,
        ));        
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Product;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Product'])) {
            $model->attributes = $_POST['Product'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Product');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Product('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Product']))
            $model->attributes = $_GET['Product'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Product::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionSearch() {
        if (isset($_POST['Product'])) {
            $criteria = new CDbCriteria();
            $criteria->compare('name', $_POST['Product']['name'], true);
            $criteria->compare('brand_id', $_POST['Product']['brand'], true, 'OR');
            $criteria->compare('category_id', $_POST['Product']['category'], true, 'AND');

            if ($_POST['Product']['price'] != 0) {
                switch ($_POST['Product']['price']) {
                    case '1':
                        $criteria->compare('price', '<500000', true);
                        break;
                    case '500000':
                        $criteria->addBetweenCondition('price', 500000, 1000000);
                        break;
                    case '1000000':
                        $criteria->addBetweenCondition('price', 1000000, 2000000);
                        break;
                    case '2000000':
                        $criteria->addBetweenCondition('price', 2000000, 3000000);
                        break;
                    case '3000000':
                        $criteria->addBetweenCondition('price', 3000000, 4000000);
                        break;
                    case '4000000':
                        $criteria->addBetweenCondition('price', 4000000, 5000000);
                        break;
                    case '5000000':
                        $criteria->compare('price', '>' . $_POST['Product']['price'], true);
                        break;
                }
            }
            $product = Product::model()->findAll($criteria);

            //group product by category
            $criteria->group = 'category_id';
            $productGroup = Product::model()->findAll($criteria);

            $this->render('searchResult', array(
                'product' => $product,
                'productGroup' => $productGroup,
                'params' => $_POST['Product'],
            ));
        }
    }

    public function actionCategory($id) {
        $product = Product::model()->findAll(array(
            'condition' => 'category_id = :id',
            'params' => array(
                ':id' => $id,
            )
        ));

        $this->render('category', array(
            'category' => $id,
            'product' => $product,
        ));
    }

}